package com.laf.controller;

import com.github.pagehelper.Page;
import com.laf.model.*;
import com.laf.service.ApplyService;
import com.laf.service.LeaveService;
import com.laf.service.NoticeService;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.ServletContextAware;
import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author: He Changjie  on  2018-09-29
 * @description:
 */
@Controller
@RequestMapping("/notice")
public class NoticeController implements ServletContextAware {

    @Resource
    NoticeService noticeService;

    @Resource
    LeaveService leaveService;

    @Resource
    ApplyService applyService;

    /**Servlet容器对象，通过 ServletContextAware 接口注入*/
    ServletContext servletContext;

    @RequestMapping("/leave")
    public String leave(Leave leave, String code, HttpSession session, ModelMap modelMap){
        String vcode = (String) session.getAttribute("vcode");
        if(code != null && !code.equalsIgnoreCase(vcode)){
            modelMap.addAttribute(noticeService.findById(leave.getNoticeId()));
            modelMap.addAttribute("content",leave.getContent());
            modelMap.addAttribute("leaveList",leaveService.findByNoticeId(leave.getNoticeId()));
            return "forward:/views/laf-detail.jsp?status=error";
        }
        leaveService.save(leave);
        return "forward:/notice/detail"+leave.getNoticeId();
    }

    @RequestMapping("/gain")
    @ResponseBody
    public String gain(Apply apply,HttpSession session){
        if(1==applyService.save(new Apply(null,apply.getProposer(),apply.getNoticeId(),null,null,null))){
            Userinfo Userinfo= (com.laf.model.Userinfo) session.getAttribute("logUser");
            return "{\"phone\":\"" + Userinfo.getPhone() + "\",\"email\":\""+Userinfo.getEmail()+"\"}";
        }
        return "{\"phone\":\"获取失败\",\"email\":\"获取失败\"}";
    }

    @RequestMapping("/query{type}")
    public String query(Notice notice, Integer pageNum, HttpSession session,@PathVariable Integer type){
        Page<Notice> page= null;
        if(pageNum==null){//点击筛选
           page=(Page<Notice>) noticeService.selectByPage(notice, 1, 15, type);
        }else{//点击翻页
            notice= (Notice) session.getAttribute("Notice");
            page=(Page<Notice>) noticeService.selectByPage(notice, pageNum, 15, type);
        }
        session.setAttribute("Notice",notice);
        session.setAttribute("Page",page);
        if(type==1){
            return "redirect:/views/laf-found.jsp";
        }else if(type==0){
            return "redirect:/views/laf-lost.jsp";
        }else{
            return "redirect:/views/laf-result.jsp";
        }
    }

    @RequestMapping("/detail{noticeId}")
    public String detail(@PathVariable String noticeId, ModelMap modelMap){
        modelMap.addAttribute("notice",noticeService.findById(noticeId));
        modelMap.addAttribute("leaveList",leaveService.findByNoticeId(noticeId));
        return "forward:/views/laf-detail.jsp";
    }

    @RequestMapping("/save")
    public String save(Notice notice,String code,String update,ModelMap modelMap, HttpSession session) throws IOException {
        String realPath = servletContext.getRealPath("/image/upload/");
        String vcode = (String) session.getAttribute("vcode");
        if(code != null && !code.equalsIgnoreCase(vcode)){
            modelMap.addAttribute(notice);
            if(update != null) {
                modelMap.addAttribute(update);
            }
            if("1".equals(notice.getType())) {
                return "forward:/views/publish-found.jsp?status=error";
            }else{
                return "forward:/views/publish-lost.jsp?status=error";
            }
        }

        // 更新状态
        if("update".equals(update)){
            if(notice.getImage1()!=null && notice.getImage1().length()>100){
                String fileName = Base64.GenerateImage(notice.getImage1(), realPath);
                if(fileName != null){
                    notice.setImage1(fileName);
                }
            }else{
                notice.setImage1(StringUtils.substringBefore(notice.getImage1(),","));
            }
            if(notice.getImage2()!=null && notice.getImage2().length()>100){
                String fileName = Base64.GenerateImage(notice.getImage2(), realPath);
                if(fileName != null){
                    notice.setImage2(fileName);
                }
            }
            if(notice.getImage3()!=null && notice.getImage3().length()>100){
                String fileName = Base64.GenerateImage(notice.getImage3(), realPath);
                if(fileName != null){
                    notice.setImage3(fileName);
                }
            }
            noticeService.update(notice);
            return "redirect:/laf/showIndex";
        }else{
            //新增状态
            String fileName1 = Base64.GenerateImage(notice.getImage1(), realPath);
            if(fileName1 != null){
                notice.setImage1(fileName1);
            }
            String fileName2=Base64.GenerateImage(notice.getImage2(),realPath);
            if(fileName2 != null){
                notice.setImage2(fileName2);
            }
            String fileName3=Base64.GenerateImage(notice.getImage3(),realPath);
            if(fileName3 != null){
                notice.setImage3(fileName3);
            }

            int save = noticeService.save(notice);
            if(save==1) {
                return "redirect:/notice/detail" + notice.getNoticeId();
            }else{
                return "redirect:/laf/showIndex";
            }
        }
    }

    @RequestMapping("/manager")
    public String manager(ModelMap modelMap, @RequestParam String id, @RequestParam int op, @RequestParam String pwd){
        Notice notice=noticeService.findById(id);
        if(pwd.equals(notice.getPhone())){
            //1删除 2修改
            if(op==1) {
                noticeService.delete(Integer.parseInt(id));
                return "redirect:/laf/showIndex";
            }else{
                if("1".equals(notice.getType())){
                    modelMap.addAttribute("id",id);
                    return "forward:/laf/showPublishFound";
                }else{
                    modelMap.addAttribute("id",id);
                    return "forward:/laf/showPublishLost";
                }

            }
        }else{
            modelMap.addAttribute("status",false);
            return "forward:/notice/detail"+id;
        }
    }

    @Override
    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

}
